<template>
  <div class="app-container">
    <div class="form-adapt-container">
      <el-card shadow="never" header="查询条件">
        <div slot="header" class="clearfix">
          <div class="medium-font-size">
            {{ queryConfig.name }}
          </div>
          <div class="text-placeholder-color mt10">
            {{ queryConfig.description }}
          </div>
        </div>
        <el-form size="small" label-width="100px" @submit.native.prevent>
          <el-row :gutter="35">
            <el-col v-for="item in queryFields" :key="item.value" :xs="24" :sm="12" :md="8" :lg="6" :xl="4"
                    class="mb20"
            >
              <el-form-item :label="item.label">
                <el-input v-model="queryParams.queryParams[item.value]" placeholder="请输入" clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
              <el-form-item>
                <el-button type="primary" icon="iconfont icon-biaodan" @click="handleQueryData">
                  查询
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
    <div v-if="!noOpenQuery">
      <base-table
        v-if="queryConfig.config&&queryConfig.config.styleType=== 'TABLE'"
        ref="publicQueryTable"
        class="mt10"
        :grid-options="gridOptions"
      >
        <template #operate="{ row }">
          <vxe-button v-if="openReply" icon="el-icon-bell" title="回复" circle @click="openReplyDrawer(row)" />
          <vxe-button v-if="queryConfig.config&&queryConfig.config.allowModify" icon="el-icon-edit" status="primary"
                      title="修改" circle @click="handleOpenEdit(row)"
          />
        </template>
      </base-table>
      <el-tabs v-if="queryConfig.config&&queryConfig.config.styleType=== 'CARD'&&queryDataList.length>0"
               class="mt10"
               type="border-card"
      >
        <el-tab-pane v-for="(form,index) in queryDataList" :key="index" :label="`结果${index+1}`">
          <generate-form
            v-if="formConf.fields.length"
            :form-conf="formConf"
            :page-form-model="form"
            style="margin-bottom: 40px"
          />
          <vxe-button v-if="openReply" icon="el-icon-bell" title="回复" circle @click="openReplyDrawer(form)" />
          <vxe-button v-if="queryConfig.config&&queryConfig.config.allowModify" icon="el-icon-edit" status="primary"
                      title="修改" circle @click="handleOpenEdit(form)"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-result v-else icon="error" title="公开查询" sub-title="暂未开启公开查询">
      <template slot="extra" />
    </el-result>
    <el-dialog
      title="修改"
      :visible.sync="dialogFormVisible"
      width="30%"
    >
      <generate-form
        v-if="formConf.fields.length"
        ref="generateForm"
        :form-conf="formConf"
        :page-form-model="editFormData"
        style="margin-bottom: 40px"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleUpdateFormData">
          修改
        </el-button>
        <el-button @click="dialogFormVisible=false">
          取消
        </el-button>
      </div>
    </el-dialog>

    <reply-drawer v-if="selectDataId" ref="replyDrawer" :form-key="formKey" :data-id="selectDataId" />
  </div>
</template>

<script>

import BaseTable from "./BaseTable"
import ReplyDrawer from "./ReplyDrawer"
import {formatTableColumn} from "./formatTableColumn"
import GenerateForm from "@/formgen/src/components/GenerateForm/GenerateForm"
import {getPublicQueryContentRequest, listPublicQueryDataRequest} from "../../../api/project/publish"
import {getPublicSettingsRequest, getSettingRequest} from "../../../api/project/setting"
import {removeHtmlTag} from "../../../formgen/src/utils"
import {jsonSimpleClone} from "../../../utils"
import {updateFormDataRequest} from "../../../api/project/data"

export default {
  name: 'PublicQuery',
  components: {
    BaseTable,
    GenerateForm,
    ReplyDrawer
  },
  data() {
    return {
      editFormData: {},
      dialogFormVisible: false,
      noOpenQuery: false,
      formKey: '',
      queryId: null,
      gridOptions: {
        border: true,
        stripe: true,
        resizable: true,
        showHeaderOverflow: true,
        showOverflow: true,
        highlightHoverRow: true,
        keepSource: true,
        id: 'publicQueryGrid',
        rowId: 'id',
        pagerConfig: {
          pageSize: 10,
          pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000]
        },
        proxyConfig: {
          autoLoad: false, // 不自动加载数据
          seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
          // 对应响应结果 { result: [], page: { total: 100 } }
          props: {
            result: 'data.rows', // 配置响应结果列表字段
            total: 'data.total' // 配置响应结果总页数字段
          },
          ajax: {
            // 接收 Promise 对象
            query: ({page, sorts, filters, form}) => {
              this.queryParams.size = page.pageSize
              this.queryParams.current = page.currentPage - 1
              this.queryParams.formKey = this.formKey
              this.queryParams.queryId = this.queryId
              this.queryParams.queryParams = this.removeEmptyParams()
              return listPublicQueryDataRequest(this.queryParams)
            }
          }
        },
        columns: []
      },
      openReply: false,
      queryConfig: {
        config: {
          allowModify: false
        }
      },
      queryFields: [],
      showFields: [],
      selectDataId: null,
      queryParams: {
        formKey: '',
        queryId: null,
        queryParams: {}
      },
      queryDataList: [],
      formConf: {
        fields: [],
        formKey: "",
        disabled: true,
        span: 24,
        size: "small",
        labelPosition: "top",
        labelWidth: 100,
        formRules: "rules",
        gutter: 15,
        formBtns: false,
        resetBtn: false,
        theme: {
          backgroundImg: "",
          showTitle: true,
          showDescribe: true,
          showNumber: false,
          btnsColor: null
        }
      }
    }
  },
  async created() {
    this.formKey = this.$route.query.key || this.$route.params.key
    this.queryId = this.$route.query.qid || this.$route.params.qid
    await this.queryUserProjectSetting()
    this.handleQueryFields()
  },
  methods: {
    // 查询设置 是否开启回复
    queryUserProjectSetting() {
      getPublicSettingsRequest(this.formKey).then((res) => {
        if (res.data) {
          this.openReply = res.data.openReply
        }
      })
    },
    // 删除为空参数
    removeEmptyParams() {
      let params = this.queryParams.queryParams
      for (let key in params) {
        if (params[key] === '') {
          delete params[key]
        }
      }
      return params
    },
    handleQueryFields() {
      getPublicQueryContentRequest(this.formKey, this.queryId).then((res) => {
        if (0 === res.data.status) {
          this.noOpenQuery = true
        }
        this.showFields = res.data.showFields
        this.queryFields = res.data.queryFields
        this.queryConfig = res.data.queryConfig
        this.handleTableColumns(res.data.showFields)
        // 问卷字段配置
        this.formConf.fields = res.data.showFields.filter((item) => {
          return item.scheme
        }).map((item) => {
          if (item.scheme) {
            item.scheme.viewMode = true
            // 去除标签中富文本
            item.scheme.config.label = removeHtmlTag(item.scheme.config.label)
          }
          return item.scheme
        })
        this.queryConfig = res.data.queryConfig
      })
    },
    handleQueryData() {
      let flag = false
      this.queryFields.forEach((item) => {
        // 没输入
        if (!this.queryParams.queryParams[item.value]) {
          flag = true
        }
      })
      const inputAllCondition = this.queryConfig.config.inputAllCondition
      if (flag && inputAllCondition) {
        this.msgError('请输入全部条件')
        return
      }
      if (this.queryConfig.config.styleType === 'TABLE') {
        this.$refs.publicQueryTable.getXGrid().commitProxy('reload')
      } else {
        this.handleQueryDataList()
      }
    },
    handleQueryDataList() {
      this.queryParams.size = 100
      this.queryParams.current = 0
      this.queryParams.formKey = this.formKey
      this.queryParams.queryId = this.queryId
      this.queryParams.queryParams = this.removeEmptyParams()
      listPublicQueryDataRequest(this.queryParams).then((res) => {
        this.queryDataList = res.data.rows
      })
    },
    handleOpenEdit(item) {
      this.editFormData = item
      this.dialogFormVisible = true
      this.formConf.disabled = false
    },
    /**
     * 格式化处理表格数据
     */
    handleTableColumns(fields) {
      // 部分组件格式化显示 Json
      // let firstCol = [{type: 'checkbox', width: 60}]
      this.gridOptions.columns = fields.map((item) => {
        return formatTableColumn(item)
      })
      // 拼接固定列
      if (this.openReply || this.queryConfig.config.allowModify) {
        this.gridOptions.columns.push({title: '操作', width: 120, fixed: 'right', slots: {default: 'operate'}})
      }
    },
    openReplyDrawer(row) {
      this.selectDataId = row.id
      this.$nextTick(() => {
        this.$refs.replyDrawer.open()
      })
    },
    handleUpdateFormData() {
      let formModel = jsonSimpleClone(this.$refs.generateForm.formModel)
      // 问卷中字段名规则为字段类型时间戳 移除不符合规则的数据 不然会有其他的比如提交时间等数据
      let tempFormModel = {}
      // 保留formModel中包含数字的属性
      for (let key in formModel) {
        let bool = /.*\d+.*/g.test(key)
        if (bool) {
          tempFormModel[key] = formModel[key]
        }
      }
      updateFormDataRequest({
        id: formModel.id,
        completeTime: null,
        formKey: this.formKey,
        submitOs: "",
        submitBrowser: "",
        submitUa: null,
        wxUserInfo: null,
        wxOpenId: "",
        originalData: tempFormModel
      }).then((res) => {
        this.msgSuccess("修改成功")
        this.dialogFormVisible = false
        this.formConf.disabled = true
      })
    }
  }

}
</script>

<style lang="scss" scoped>
.app-container {
  width: 100%;
}

::v-deep .project-form {
  background-color: #FFFFFF !important;
  width: 100% !important;
}

::v-deep .vxe-export--panel tr:last-child {
  display: none !important;
}

@media screen and (max-width: 500px) {
  ::v-deep .vxe-pager {
    padding-top: 30px !important;
  }
  ::v-deep .vxe-modal--box {
    width: 100% !important;
  }
  ::v-deep .el-dialog__wrapper .el-dialog {
    width: 100% !important;
  }
  ::v-deep .vxe-toolbar {
    display: flex;
    flex-wrap: wrap;
    padding-bottom: 10px;
    height: 100px;

    &:last-child .el-button {
      margin-left: 0px;
    }

    .vxe-toolbar {
      margin-top: 10px;
    }
  }

}

</style>
